package com.peaksport.framework.util;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map;

import org.apache.servicecomb.swagger.invocation.context.ContextUtils;
import org.apache.servicecomb.swagger.invocation.context.InvocationContext;

import com.peaksport.framework.exception.PKBizException;
import com.peaksport.framework.exception.PKDevException;
import com.peaksport.framework.extend.redis.PKRedisTemplate;
import com.peaksport.framework.extend.redis.venum.ExpireTimeType.ExpireTimeEnum;
import com.peaksport.framework.vo.SessionInfo;

import lombok.extern.slf4j.Slf4j;

/**
 * 上下文操作工具类
 * 
 * 
 * 
 * @author jinbin_guo  2019年6月4日 下午5:10:09
 *
 */
@Slf4j
public class PKContextUtils {
	
	/** 在redis中sesionId的分组前缀*/
	public static final String session_redis_prefixKey = "PKMS:Session";
	/** sessionId在context直接传递字串*/
	public static final String session_context_key = "sessionId";
	
	/**
	 * 获取传递调用过程的上下文数据
	 * @return
	 */
	private static InvocationContext getInvocationContext() {
		return ContextUtils.getInvocationContext();
	}
	
	/**
	 * 
	 * @param key
	 * @return
	 */
	public static String getContext(String key) {
		return  getInvocationContext().getContext(key);
	}
	public static Map<String,String> getContext() {
		return getInvocationContext().getContext();
	}
	
	public static void addContext(String key, String value) {
		getInvocationContext().addContext(key, value);
	}
	public static void addContext(Map<String,String> otherContext) {
		getInvocationContext().addContext(otherContext);
	}
	public static void setContext(Map<String,String> context) {
		getInvocationContext().setContext(context);
	}
	
	
	/**
	 * 获取session 会话信息
	 * @return
	 */
	public static SessionInfo getSessionInfo(PKRedisTemplate pkRedisTemplate) {
		String sessionId = PKContextUtils.getContext(session_context_key);
		if (PKPublicUtils.isEmpty(sessionId)) 
			throw PKDevException.throwException("服务间session传递异常");
		SessionInfo sessionInfo = (SessionInfo) pkRedisTemplate.getObject(session_redis_prefixKey, sessionId);
		if (sessionInfo == null) 
			throw PKBizException.throwException("session[%d]已经过期,请重新登录",sessionId);
		return sessionInfo;
	}
	
	
	/**
	 * 存放contextInfo 会话信息
	 * @param contextInfo
	 */
	public static void setSessionInfo(PKRedisTemplate pkRedisTemplate,SessionInfo sessionInfo) {
		 if (sessionInfo == null)
			 throw PKDevException.throwException("会话信息对象不能为空.");
		//存放redis 
		String sessionId = sessionInfo.getSessionId();
		pkRedisTemplate.setObject(session_redis_prefixKey, sessionId, sessionInfo, ExpireTimeEnum.expire_1h.getValue());
	}

	
	

}
